
const BASE_62_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
const BASE = BASE_62_CHARS.length;
const BASE_BIG = BigInt(BASE_62_CHARS.length);

/**
 * 将10进制数字转换为62进制字符串
 * @param num 10进制整数 (0 ≤ num ≤ Number.MAX_SAFE_INTEGER)
 * @returns 62进制字符串
 */
export function toBase62(num: number): string {
    if (num === 0) return '0';
    if (num < 0) throw new Error('负数转换未实现');
    if (num > Number.MAX_SAFE_INTEGER) {
        throw new Error(`超出安全整数范围 (max: ${Number.MAX_SAFE_INTEGER})`);
    }
    
    let result = '';
    while (num > 0) {
        const remainder = num % BASE;
        num = Math.floor(num / BASE);
        result = BASE_62_CHARS[remainder] + result;
    }
    return result;
}

/**
 * 将62进制字符串转换为10进制数字
 * @param str 62进制字符串（仅包含0-9, a-z, A-Z）
 * @returns 10进制整数
 */
export function toBase10(str: string): number {
    if (str === '') throw new Error('输入不能为空字符串');
    if (str === '0') return 0;
    
    let result = 0;
    const base = BASE;
    
    for (let i = 0; i < str.length; i++) {
        const char = str[i];
        const charValue = BASE_62_CHARS.indexOf(char);
        
        if (charValue === -1) {
            throw new Error(`无效字符 '${char}'，只能使用0-9, a-z, A-Z`);
        }
        
        const power = str.length - i - 1;
        result += charValue * Math.pow(base, power);
        
        // 检查是否超出安全整数范围
        if (result > Number.MAX_SAFE_INTEGER) {
            throw new Error(`转换结果超出安全整数范围 (max: ${Number.MAX_SAFE_INTEGER})`);
        }
    }
    
    return result;
}

/**
 * 将10进制大整数转换为62进制字符串
 * @param num 10进制整数 (0 ≤ num ≤ Number.MAX_SAFE_INTEGER)
 * @returns 62进制字符串
 */
export function toBase62Big(num: bigint): string {
    if (num === 0n) return '0';
    if (num < 0n) throw new Error('负数转换未实现');
    
    let result = '';
    let n = num;
    while (n > 0n) {
        const remainder = n % BASE_BIG;
        n = n / BASE_BIG;
        result = BASE_62_CHARS[Number(remainder)] + result;
    }
    return result;
}

/**
 * 将62进制字符串转换为10进制大整数
 * @param str 62进制字符串（仅包含0-9, a-z, A-Z）
 * @returns 10进制整数
 */
export function toBase10Big(str: string): bigint {
    if (str === '') throw new Error('输入不能为空字符串');
    if (str === '0') return 0n;
    
    let result = 0n;
    const base = BASE_BIG;
    
    for (let i = 0; i < str.length; i++) {
        const char = str[i];
        const charValue = BASE_62_CHARS.indexOf(char);
        
        if (charValue === -1) {
            throw new Error(`无效字符 '${char}'，只能使用0-9, a-z, A-Z`);
        }
        
        const power = BigInt(str.length - i - 1);
        result += BigInt(charValue) * (base ** power);
    }
    
    return result;
}